package sword_offer;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Synhard
 * @version 1.0
 * @class Code58
 * @description 剑指 Offer 54. 二叉搜索树的第k大节点
 * 给定一棵二叉搜索树，请找出其中第k大的节点。
 *
 *  
 *
 * 示例 1:
 *
 * 输入: root = [3,1,4,null,2], k = 1
 *    3
 *   / \
 *  1   4
 *   \
 *    2
 * 输出: 4
 * 示例 2:
 *
 * 输入: root = [5,3,6,2,4,null,null,1], k = 3
 *        5
 *       / \
 *      3   6
 *     / \
 *    2   4
 *   /
 *  1
 * 输出: 4
 *  
 *
 * 限制：
 *
 * 1 ≤ k ≤ 二叉搜索树元素个数
 *
 * @tel 13001321080
 * @email 823436512@qq.com
 * @date 2021-07-14 7:57
 */
public class Code58 {
    public static void main(String[] args) {

    }

    public int kthLargest(TreeNode root, int k) {
        Deque<TreeNode> stack = new LinkedList<>();
        List<Integer> list = new ArrayList<>();
        stack.addFirst(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.peekFirst();
            if (cur != null) {
                stack.removeFirst();
                if (cur.right != null) {
                    stack.addFirst(cur.right);
                }
                stack.addFirst(cur);
                stack.addFirst(null);
                if (cur.left != null) {
                    stack.addFirst(cur.left);
                }
            } else {
                stack.removeFirst();
                list.add(stack.removeFirst().val);
            }
        }
        return list.get(list.size() - k);
    }

}
